package com.sundablog.service.impl.backend.index;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sundablog.pojo.AdminPermission;
import com.sundablog.pojo.AdminRolePermission;
import com.sundablog.pojo.AdminUserRole;
import com.sundablog.result.MenuResult;
import com.sundablog.service.backend.index.IndexService;
import com.sundablog.service.backend.system.upms.permissions.PermissionsService;
import com.sundablog.service.backend.system.upms.role.RoleService;
import com.sundablog.service.backend.system.upms.user.UserService;

/**
 * 首页接口实现类
 * @ClassName:  IndexServiceImpl   
 * @Description:TODO(这里用一句话描述这个类的作用)   
 * @author: 哒哒 
 * @date:   2018年3月30日 下午5:30:13   
 *     
 * @Copyright: 2018 www.sundablog.com Inc. All rights reserved.
 */
@Service
public class IndexServiceImpl implements IndexService {
	
	@Autowired
	private RoleService roleService;

	@Autowired
	private UserService userService;
	
	@Autowired
	private PermissionsService permissionsService;
	
	@Override
	public List<MenuResult> getMenuResult(Integer userId) {
		//用户角色关联的信息
		AdminUserRole userRole = userService.selectByUserId(userId);
		
		List<AdminRolePermission> adminRolePermissions = roleService.selectRolePermissionByRoleId(userRole.getRoleId());
		
		List<MenuResult> menuResults = new ArrayList<>();
		for (AdminRolePermission adminRolePermission : adminRolePermissions) {
			AdminPermission adminPermission = permissionsService.selectPermissionsByPermissionId(adminRolePermission.getPermissionId());
			if (adminPermission.getType() != 3) {
				MenuResult menuResult = new MenuResult();
				menuResult.setId(adminPermission.getPermissionId().toString());
				menuResult.setPid(adminPermission.getPid().toString());
				menuResult.setTitle(adminPermission.getName());
				menuResult.setIcon(adminPermission.getIcon());
				menuResult.setUrl(adminPermission.getUri());
				menuResult.setFont("larry-icon");
				menuResults.add(menuResult);
			}
		}
		List<MenuResult> trees = new ArrayList<MenuResult>(); 
		for (MenuResult menuResult : menuResults) {
			if ("0".equals(menuResult.getPid())) {  
                trees.add(findChildren(menuResult,menuResults));  
            }  
		}
		return trees;
	}
	
	/**
	 * 递归查找子节点
	 * 
	 * @param treeNodes
	 * @return
	 */
	public static MenuResult findChildren(MenuResult treeNode, List<MenuResult> treeNodes) {
		for (MenuResult it : treeNodes) {
			if (treeNode.getId().equals(it.getPid())) {
				if (treeNode.getChildren() == null) {
					treeNode.setChildren(new ArrayList<MenuResult>());
				}
				treeNode.getChildren().add(findChildren(it, treeNodes));
			}
		}
		return treeNode;
	}
	
}
